/* 
 * Copyright (c) 2011-, Agilord Kft. - All Rights Reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.agilord.dragonflyp4;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONValue;

/**
 * Main entry point
 * 
 * @author Istvan Soos
 * @since 1.0
 */
public class DragonflyP4 {

	public static void main(String[] args) throws Exception {
		// init configuration with defaults and command line
		Configuration.get().init(args);

		// scan the files and dirs from command line args
		FileScanner fs = new FileScanner(args);
		for (File photo = fs.next(); photo != null; photo = fs.next()) {
			ImageFile imageFile = new ImageFile();
			imageFile.setFile(photo);
			imageFile.setExif(getExifInfo(photo));

			System.out.println("Processing: " + photo.getAbsolutePath());
			for (ProcessModule pm : Configuration.get().getProcess())
				pm.process(imageFile);
		}

		// report summary
		for (ProcessModule pm : Configuration.get().getProcess())
			pm.reportSummary();
	}

	@SuppressWarnings("unchecked")
	public static Map<String, Object> getExifInfo(File file) {
		ProcessBuilder pb = new ProcessBuilder(
		        Configuration.get().getExiftool(),
		        "-j",
		        file.getAbsolutePath());
		pb.redirectErrorStream();
		try {
			Process proc = pb.start();
			List<Object> list = (List<Object>) JSONValue.parse(
			        new InputStreamReader(proc.getInputStream(), "utf-8"));
			proc.destroy();
			return (Map<String, Object>) list.get(0);
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}

}
